package main

import (
	"encoding/json"
	"fmt"
)

type Response[T any] struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data T      `json:"data"`
}

type User struct {
	Id int64 `json:"id"`
}

type UserInfo struct {
	User
	Name  string `json:"name"`
	Age   int    `json:"age,omitempty"`
	Phone string `json:"phone"`
}

func main() {
	user := User{
		Id: 426575435354,
	}
	userInfo := UserInfo{
		User:  user,
		Name:  "yangyang",
		Age:   23,
		Phone: "+86 13425346453",
	}
	response := Response[UserInfo]{
		Code: 0,
		Msg:  "登陆成功",
		Data: userInfo,
	}
	jsonResponse, _ := json.Marshal(response)
	//{"code":0,"msg":"登陆成功","data":{"id":426575435354,"name":"yangyang","age":23,"phone":"+86 13425346453"}}
	jsonstring := string(jsonResponse)
	fmt.Println(jsonstring)

	var userInfoResposne Response[UserInfo]
	json.Unmarshal(
		[]byte(`{"code":0,"msg":"登陆成功","data":{"id":426575435354,"name":"yangyang","age":23,"phone":"+86 13425346453"}}`),
		&userInfoResposne,
	)
	fmt.Printf("userInfoResposne: %v\n", userInfoResposne)

	//map泛型的struct与json互转

	mapStruct := Response[map[string]any]{
		Code: 0,
		Msg:  "登陆成功",
		Data: map[string]any{
			"id":      "12345676",
			"name":    "yangyang",
			"phone":   "13245465675",
			"age":     24,
			"address": "南阳市宛城区",
		},
	}
	jsonResponse, _ = json.Marshal(mapStruct)
	jsonstring = string(jsonResponse)
	fmt.Println(jsonstring)

	var mapResponse Response[map[string]string]
	json.Unmarshal(
		[]byte(`{"code":0,"msg":"登陆成功","data":{"address":"南阳市宛城区","age":"24","id":"12345676","name":"yangyang","phone":"13245465675"}}`),
		&mapResponse,
	)
	fmt.Printf("mapResponse: %v\n", mapResponse)

}
